'''The GUI to create new CSN claims, and submit existing claims.'''
from pprint import pformat as pprint_pformat
import PySimpleGUI as sg
from warranty_manager.gui.get_items import get_part_nums_gui, get_notes_gui
from warranty_manager.gui.chromebook_notes import get_chromebook_note_gui
from warranty_manager.claim.hp.csn.csn_claim_manager_layout import LAYOUT
from warranty_manager.claim.hp.csn.csn_claim import CSNClaim
from warranty_manager.claim.common import (
    get_logger, validate_claim_info, choose_note_type
)
from warranty_manager.claim.hp.csn.csn_claim_manager_functions import (
    load_claim_info, save_claim_info
)
from warranty_manager.gui.confirmation import (
    get_confirmation, get_csn_confirmation
)


CLAIM_INFO = {
    'serial number': '',
    'product number': '',
    'po number': '',
    'learner id': '',
    'ship name': '',
    'end user': '',
    'part numbers': set(),
    'notes': set(),
}

WINDOW = sg.Window('HP CSN Claim Manager', LAYOUT)

while True:
    EVENT, VALUES = WINDOW.read()

    # To close the program window
    if EVENT in (None, 'Cancel', 'Exit'):
        break

    # To save/load claim information from a file
    elif EVENT == 'Load Claim Information':
        CLAIM_INFO = load_claim_info(CLAIM_INFO, WINDOW)
    elif EVENT == 'Save Claim Information':
        save_claim_info(CLAIM_INFO, WINDOW)

    # To add, view, or replace part numbers
    elif EVENT == '-ADD_PART_NUMBERS-':
        CLAIM_INFO['part numbers'].update( get_part_nums_gui() )

        if len(CLAIM_INFO['part numbers']) > 0:
            WINDOW['-ADD_PART_NUMBERS-'].update('Add More Parts')
    elif EVENT == '-REPLACE_PART_NUMBERS-':
        confirmation = get_confirmation(
            'replace all the current part numbers with a new set of part numbers'
        )

        if confirmation:
            CLAIM_INFO['part numbers'] = get_part_nums_gui()
    elif EVENT == '-VIEW_PART_NUMBERS-':
        if len(CLAIM_INFO['part numbers']) == 0:
            sg.popup('There are no part numbers to view.', title='Info Message')
            continue

        sg.popup(
            pprint_pformat( list(CLAIM_INFO['part numbers']) ),
            title='Info Message'
        )

    # To add, view, or remove CSN notes
    elif EVENT == '-ADD_NOTES-':
        note_type = choose_note_type()

        if note_type == 'Chromebook':
            try:
                description, troubleshooting = get_chromebook_note_gui()
                CLAIM_INFO['notes'].add(f'{description} {troubleshooting}')
            except TypeError: # Chromebook issue GUI window was closed
                continue
        elif note_type == 'Non-Chromebook':
            CLAIM_INFO['notes'].update( get_notes_gui() )
        else:
            continue

        if len(CLAIM_INFO['notes']) > 0:
            WINDOW['-ADD_NOTES-'].update('Add More Notes')
    elif EVENT == '-VIEW_NOTES-':
        if len(CLAIM_INFO['notes']) == 0:
            sg.popup('There are no notes to view.', title='Info Message')
            continue

        sg.popup(
            pprint_pformat( list(CLAIM_INFO['notes']) ),
            title='Info Message'
        )
    elif EVENT == '-REMOVE_NOTES-':
        if len(CLAIM_INFO['notes']) == 0:
            sg.popup('There are no notes to remove.', title='Info Message')
            continue

        confirmation = get_confirmation('remove all CSN notes from the claim')

        if confirmation:
            CLAIM_INFO['notes'] = set()
            WINDOW['-ADD_NOTES-'].update('Add Note(s)')

    # To create a new CSN claim
    elif EVENT == 'Create':
        CLAIM_INFO['serial number'] = VALUES['-SERIAL_NUMBER-']
        CLAIM_INFO['product number'] = VALUES['-PRODUCT_NUMBER-']
        CLAIM_INFO['po number'] = VALUES['-PO_NUMBER-']
        CLAIM_INFO['learner id'] = VALUES['-LEARNER_ID-']
        CLAIM_INFO['ship name'] = VALUES['-SHIP_NAME-']
        CLAIM_INFO['end user'] = VALUES['-END_USER-']

        if validate_claim_info(CLAIM_INFO) and get_csn_confirmation(CLAIM_INFO):
            try:
                claim = CSNClaim(
                    {'url': 'https://h30125.www3.hp.com/hpcsn/', **CLAIM_INFO}
                )
                claim.create()

                # To clear the input for any fields that must change with each claim
                if not VALUES['-MULTIPLE_DEVICES-']:
                    WINDOW['-PO_NUMBER-'].update('')

                WINDOW['-SERIAL_NUMBER-'].update('')
            except claim.get_network_exceptions():
                continue
            except Exception as err:
                claim.quit_browser()
                sg.popup_error(
                    'An unexpected error has occurred. '
                    'Please check the logs for more information.',
                    title='Error Message'
                )
                get_logger('csn_claim_manager').exception(err)

    # To remove all model-specific claim info
    elif EVENT == 'Change Model':
        confirmation = get_confirmation(
            'change the device model for this claim,\n'
            'and set all model-specific fields back '
            'to their default values'
        )

        if confirmation:
            CLAIM_INFO['part numbers'] = set()
            CLAIM_INFO['notes'] = set()
            WINDOW['-PO_NUMBER-'].update('')
            WINDOW['-SERIAL_NUMBER-'].update('')
            WINDOW['-PRODUCT_NUMBER-'].update('')
            WINDOW['-ADD_NOTES-'].update('Add Note(s)')
            WINDOW['-ADD_PART_NUMBERS-'].update('Add Part(s)')

    # To submit all Columbus City Schools CSN claims
    elif EVENT == 'Submit':

        if get_confirmation('submit all applicable Columbus City Schools CSN warranty claims'):
            try:
                claim = CSNClaim(
                    {'url': 'https://h30125.www3.hp.com/hpcsn/', **CLAIM_INFO}
                )
                claim.submit()
            except claim.get_network_exceptions():
                continue
            except Exception as err:
                claim.quit_browser()
                sg.popup_error(
                    'An unexpected error has occurred. '
                    'Please check the logs for more information.',
                    title='Error Message'
                )
                get_logger('csn_claim_manager').exception(err)

    # To ignore any other events
    else:
        continue

WINDOW.close()
